package com.library.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.library.entity.Book;
import com.library.mapper.BookMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 图书服务
 */
@Service
@RequiredArgsConstructor
public class BookService extends ServiceImpl<BookMapper, Book> {

    private final BookMapper bookMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    private static final String HOT_BOOKS_KEY = "library:hot_books";

    /**
     * 分页查询图书
     */
    public Page<Book> pageBooks(Integer current, Integer size, String title,
                                String author, Long categoryId) {
        Page<Book> page = new Page<>(current, size);
        return bookMapper.selectBookPage(page, title, author, categoryId);
    }

    /**
     * 获取热门图书（使用Redis缓存）
     */
    @SuppressWarnings("unchecked")
    public List<Book> getHotBooks(Integer limit) {
        // 先从缓存获取
        List<Book> hotBooks = (List<Book>) redisTemplate.opsForValue().get(HOT_BOOKS_KEY);

        if (hotBooks == null) {
            // 缓存未命中，从数据库查询
            hotBooks = bookMapper.selectHotBooks(limit);
            // 存入缓存，过期时间1小时
            redisTemplate.opsForValue().set(HOT_BOOKS_KEY, hotBooks, 1, TimeUnit.HOURS);
        }

        return hotBooks;
    }

    /**
     * 添加图书
     */
    public void addBook(Book book) {
        // 设置可借库存等于总库存
        book.setAvailableStock(book.getTotalStock());
        book.setBorrowCount(0);
        this.save(book);

        // 清除热门图书缓存
        redisTemplate.delete(HOT_BOOKS_KEY);
    }

    /**
     * 更新图书
     */
    public void updateBook(Book book) {
        this.updateById(book);

        // 清除热门图书缓存
        redisTemplate.delete(HOT_BOOKS_KEY);
    }

    /**
     * 删除图书
     */
    public void deleteBook(Long id) {
        this.removeById(id);

        // 清除热门图书缓存
        redisTemplate.delete(HOT_BOOKS_KEY);
    }

    /**
     * 检查图书是否可借
     */
    public boolean isBookAvailable(Long bookId) {
        Book book = this.getById(bookId);
        return book != null && book.getAvailableStock() > 0;
    }

    /**
     * 减少可借库存
     */
    public void decreaseStock(Long bookId) {
        Book book = this.getById(bookId);
        if (book.getAvailableStock() <= 0) {
            throw new RuntimeException("图书库存不足");
        }

        book.setAvailableStock(book.getAvailableStock() - 1);
        book.setBorrowCount(book.getBorrowCount() + 1);
        this.updateById(book);

        // 清除热门图书缓存
        redisTemplate.delete(HOT_BOOKS_KEY);
    }

    /**
     * 增加可借库存
     */
    public void increaseStock(Long bookId) {
        Book book = this.getById(bookId);
        book.setAvailableStock(book.getAvailableStock() + 1);
        this.updateById(book);
    }
}

